package api

import (
	"gitee.com/gcom/stockdock/comm"
	"gitee.com/gcom/stockdock/core/job"
	"gitee.com/gcom/stockdock/core/router"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/spider/ths"
	"net/http"
)

func init() {
	router.ApiRouter.HandleFunc("/comp/list", listCompany).Methods("GET")
	router.ApiRouter.HandleFunc("/comp/show", getCompany).Methods("GET")
	router.AdminRouter.HandleFunc("/comp/updateAll", updateAll).Methods("GET")
}

// 查询上市企业列表
func listCompany(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	q := &ths.CompanyQuery{}
	if !s.ParseAndValidQuery(ctx, q) {
		return
	}

	list, err := ths.GetCompanyList(ctx.DB, q)
	if err != nil {
		s.ResError(ctx, 400, err)
		return
	}
	s.ResOk(ctx, list)
}

// 查询单个上市公司信息
func getCompany(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	q := r.URL.Query()["code"]
	if len(q) == 0 || !comm.StockCodePtn.Match([]byte(q[0])) {
		s.ResFail(ctx, 400, "请填写有效股票代码")
		return
	}

	comp, err := ths.GetCompany(ctx.DB, q[0])
	if err != nil {
		s.ResError(ctx, 500, err)
		return
	}
	s.ResOk(ctx, comp)
}

// 全量更新上市公司信息
func updateAll(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	job.JobThsCompany.Run(ctx)
}
